package cums.db.impl;

import cums.db.iface.CustomersDao;
import cums.db.pers.Customers;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * @time Dec 9, 2009, 12:57:16 PM
 * @author fdcube
 */
public class CustomersImpl extends HibernateDaoSupport implements CustomersDao {

    public Customers AddOrUpdateCustomers(Customers value) {
        this.getHibernateTemplate().saveOrUpdate(value);
        return value;
    }

    public boolean DeleteCustomers(Customers value) {
        try {
            this.getHibernateTemplate().delete(value);
            return true;
        } catch (DataAccessException dataAccessException) {
            logger.error(dataAccessException);
            return false;
        }
    }

    public List<Customers> ListCustomers() {
        return this.getHibernateTemplate().find("FROM CUSTOMERS ORDER BY CID");
    }

    public List<Customers> FindCustomersById(int value) {
        return this.getHibernateTemplate().findByNamedParam("FROM customers AS c WHERE c.CID =:value", "value", value);
    }

    public List<Customers> FindCustomersByName(String value) {
        return this.getHibernateTemplate().findByNamedParam("FROM CUSTOMERS AS c WHERE c.CNAME =:value", "value", value);
    }

    public List<Customers> getListForPage(final String hql, final int offset, final int length) {

        List<Customers> list = getHibernateTemplate().executeFind(
                new HibernateCallback() {

                    public Object doInHibernate(Session session) throws HibernateException, SQLException {
                        Query query = session.createQuery(hql);
                        query.setFirstResult(offset);
                        query.setMaxResults(length);
                        List list = query.list();
                        return list;
                    }
                });
        return list;
    }

    public List<Customers> ShowCustomersByGid(int page, int gid, int uid) {
        String hql = "FROM CUSTOMERS AS c WHERE c.GID = " + gid + "AND c.UID = " + uid;
        return this.getListForPage(hql, page * 10, 10);
    }

    public List<Customers> ShowCustomersByUid(int page, int uid) {
        String hql = "FROM Customers AS c WHERE c.users.uid = " + uid;
        return this.getListForPage(hql, page * 10, 10);
    }
}
